import { getLocalStore, setLocalStore } from '../advertiseService';
import { indexPage, timeOutPattern,preventedLocalStoreKeys, defaultHtmlAdvertiseEmptyContent, defaultHtmlAdvertiseId, defaultHtmlAdvertiseCode, onHtmlAdvertiseUnLoad, APP_SHOW_LOADED_ADVERTISE_EVENT, getAds, advertiseUrl, htmlAdvertiseEventHandlerConfig } from '../advertiseConfiguration';
import _ from 'lodash-es';


Page({
  data: {
    id: defaultHtmlAdvertiseId,
    url: indexPage,
    advertiseUrl,
  },
  async onLoad({ advertiseCode, defaultAdvertiseCode = defaultHtmlAdvertiseCode, entry = true }) {
    const self = this;
    self.setData({ entry: entry === true });
    if (self.data.entry) {
      self.dealEntryPage();
      return;
    }
    // 消息队列缓存onLoad时进来的消息
    self.messageQueue = [];
    let adList = await getAds(advertiseCode);
    if (_.isEmpty(adList)) {
      adList = await getAds(defaultAdvertiseCode);
    }
    if (_.size(adList) === 0) {
      return;
    }
    const isIntroduce = _.includes([advertiseCode, defaultAdvertiseCode], 'adMobileHtmlIntroduce');
    const adContent = isIntroduce ? adList[_.random(0, adList.length - 1)] : adList[0];
    await setLocalStore({ key: preventedLocalStoreKeys.advertise, data: adContent });
    self.setData({ advertise: adContent });
    const messageList = self.messageQueue;
    delete self.messageQueue;
    if (messageList.length > 0) {
      _.each(messageList, (ele) => self.doHandleMessage(ele));
    }
  },
  onUnload() {
    onHtmlAdvertiseUnLoad(this.data.entry);
    if (!this.data.entry) {
      return;
    }
    my.off(APP_SHOW_LOADED_ADVERTISE_EVENT);
    if (this.data.timeoutId) {
      clearTimeout(this.data.timeoutId);
    }
  },
  setAdTimeOut(adv) {
    const self = this;
    const timeout = self.parseTimeout(adv.content);
    if (timeout) {
      const timeoutId = setTimeout(() => self.closeHtmlAd(), _.max([timeout, 2000]));
      self.setData({ timeoutId });
    }
  },
  parseTimeout(ad = '') {
    const timeoutMatches = ad.match(timeOutPattern);
    if (timeoutMatches && timeoutMatches.length > 1) {
      return parseInt(timeoutMatches[1], 10);
    }
  },
  dealEntryPage() {
    const self = this;
    self.setData({
      advertise: {
        content: defaultHtmlAdvertiseEmptyContent,
      },
    });
    my.on(APP_SHOW_LOADED_ADVERTISE_EVENT, ({ advertise, url }) => {
      self.setData({ advertise, url });
      self.setAdTimeOut(advertise);
      self.postAdHtmlContent(true);
    });
  },
  postMessageToH5(message) {
    this.webViewContext = my.createWebViewContext(this.data.id);
    this.webViewContext.postMessage(message);
  },
  async postAdHtmlContent(animation = false) {
    const self = this;
    const { advertise } = self.data;
    if (advertise) {
      self.postMessageToH5({ data: advertise, animation });
      return;
    }
    const { data } = await getLocalStore(preventedLocalStoreKeys.advertise);
    self.postMessageToH5({ data, animation });
  },
  async handleMessage(e) {
    const dataInMsg = _.get(e, 'detail', {});
    if (dataInMsg.action) {
      this.doHandleMessage(dataInMsg);
      return;
    }
    const dataInLocal = await getLocalStore(preventedLocalStoreKeys.htmlAdvertiseLocalStorage);
    const { data } = dataInLocal;
    let msg = typeof data === 'string' ? JSON.parse(data) : data;
    msg = _.assign({}, msg, _.get(msg, 'APDataStorage')); // dev环境下，数据在APDataStorage中
    this.doHandleMessage(msg);
  },
  doHandleMessage(data) {
    const self = this;
    console.info('doHandleMessage', data);
    if (self.messageQueue) {
      self.messageQueue.push(data);
      return;
    }
    const dealer = htmlAdvertiseEventHandlerConfig[data.action];
    if (_.isUndefined(dealer)) {
      console.error(`unknown action ${data.action}`);
      return;
    }
    if (_.isFunction(htmlAdvertiseEventHandlerConfig)) {
      dealer.call(data.action, data);
    } else {
      console.error('ele of htmlAdvertiseEventHandlerConfig must be function!');
    }
  },
});
